<template>
  <div>
    <q-form class="dialog_card column" ref="editRef" style="padding: 15px">
      <q-tabs
        v-model="tab"
        dense
        class="text-grey"
        active-color="primary"
        indicator-color="primary"
        align="justify"
        narrow-indicator
      >
        <q-tab name="mails" label="基础设置" />
        <q-tab name="alarms" label="商品详情" />
        <q-tab name="movies" label="商品属性" />
      </q-tabs>
      <q-separator />

      <q-tab-panels v-model="tab" animated keep-alive>
        <q-tab-panel name="mails">
          <!-- {{ isform }} -->
          <div class="tabsContent">
            <div class="text-h6" style="margin-bottom: 5px">基础信息</div>
            <q-separator />
            <div class="row q-col-gutter-x-md dialog_form q-pa-md">
              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品名称：</h5>
                <q-input
                  lazy-rules
                  :rules="[
                    (val) => (val && val.length > 0) || '请输入角色描述',
                  ]"
                  outlined
                  dense
                  v-model="isform.goods_name"
                  type="text"
                  clearable
                  style="max-width: 500px"
                />
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />分类：</h5>
                <q-select
                  outlined
                  dense
                  multiple
                  :rules="[(val) => (val && val !== null) || '请选择分类']"
                  v-model="isform.category_id"
                  option-value="cat_id"
                  option-label="cat_name"
                  :options="optionsCate"
                  emit-value
                  map-options
                  style="max-width: 250px"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        No results
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品类型：</h5>
                <q-select
                  outlined
                  dense
                  :rules="[(val) => (val && val !== null) || '请选择商品类型']"
                  v-model="isform.goods_type"
                  option-value="id"
                  option-label="type_name"
                  :options="optionsGoodsType"
                  emit-value
                  map-options
                  style="max-width: 250px"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        No results
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />单位：</h5>
                <q-input
                  lazy-rules
                  :rules="[
                    (val) => (val && val.length > 0) || '请输入角色描述',
                  ]"
                  outlined
                  dense
                  v-model="isform.unit"
                  type="text"
                  clearable
                  style="max-width: 250px"
                />
              </div>

              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品主图：</h5>
                <q-btn>
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="imagePath(isform.goods_image)"
                    :preview-src-list="[imagePath(isform.goods_image)]"
                    hide-on-click-modal
                    preview-teleported
                    :initial-index="1"
                    fit="cover"
                  />
                  <yq-uploader
                    ref="yqupload"
                    @uploadedAvatar="uploadedAvatar"
                  ></yq-uploader>
                </q-btn>
                <div>
                  <q-btn
                    @click="importAvatar"
                    color="primary"
                    class="color-primary uploadBtn"
                    style="margin: 10px 0 5px 5px"
                    >点击上传</q-btn
                  >
                </div>
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品图片(可多选)：</h5>
                <!-- {{ isform.images }} -->
                <div>
                  <!-- <draggable
                    :list="isform.images"
                    item-key="index"
                    animation="300"
                  >
                    <template #item="{ element }">
                      <div>{{ element }}</div>
                    </template>
                  </draggable> -->
                </div>
                <div class="wallBox">
                  <div>
                    <draggable
                      :list="isform.images"
                      item-key="index"
                      animation="300"
                      class="wall"
                    >
                      <template #item="{ element }">
                        <div class="tpbox">
                          <!-- {{ item }} -->
                          <div class="deleteBox">
                            <q-btn
                              flat
                              round
                              dense
                              class="q-mx-xs"
                              color="negative"
                              icon="delete"
                            ></q-btn>
                          </div>
                          <el-image
                            v-if="element.type === 0"
                            style="width: 150px; height: 150px"
                            :src="imagePath(element.link)"
                            :preview-src-list="[imagePath(element.link)]"
                            hide-on-click-modal
                            preview-teleported
                            :initial-index="1"
                            fit="cover"
                          />
                          <video
                            controls
                            autoplay
                            v-if="element.type === 1"
                            style="width: 150px; height: 150px"
                            :src="imagePath(element.link)"
                          />
                        </div>
                      </template>
                    </draggable>
                  </div>
                </div>
                <!--缩略图-->
                <img class="thumbnail" />
                <!--上传图片-->
                <div class="uploadBox">
                  <el-upload
                    :show-file-list="false"
                    :auto-upload="false"
                    action="#"
                    :on-change="(file:any)=>handleThumbnailChange(file,'tp')"
                    multiple
                    ref="eleUpload"
                    accept="image/*"
                    style="margin-right: 20px"
                  >
                    <!----上传按钮--->
                    <template #trigger>
                      <el-button type="primary">上传图片</el-button></template
                    >
                  </el-upload>
                  <!--上传视频-->
                  <el-upload
                    :show-file-list="false"
                    :auto-upload="false"
                    action="#"
                    multiple
                    :on-change="(file:any)=>handleThumbnailChange(file,'video')"
                    ref="eleUploadVideo"
                    accept="video/*"
                  >
                    <!----上传按钮--->
                    <template #trigger>
                      <el-button class="ml-3" type="success">
                        上传视频
                      </el-button></template
                    >
                  </el-upload>
                </div>
              </div>
            </div>

            <div class="text-h6" style="margin-bottom: 5px">价格库存</div>
            <q-separator />

            <!-- {{ isform.goods_spec_format }}------
            {{ isform.sku }} -->

            <merge-table
              :goods_title="isform.goods_spec_format"
              :table="isform.sku"
              @Updatetable="Updatetable"
            />
            <!-- <q-btn
              unelevated
              :ripple="{ color: 'info' }"
              class="q-mt-md full-width"
              style="border: 1px dashed lightgrey"
              label="新增成员"
              icon="add"
              @click="add"
            /> -->
            <div class="text-h6" style="margin-bottom: 5px; margin-top: 25px">
              配送信息
            </div>
            <q-separator />
            <div class="postage">
              <h5 style="display: inline-block">
                <q-icon name="star" color="red" />是否免邮：
              </h5>
              <q-option-group
                v-model="isform.is_free_shipping"
                style="display: inline-block"
                :options="[
                  { value: 1, label: '是' },
                  { value: 0, label: '否' },
                ]"
                color="primary"
                inline
              />
            </div>
            <div class="text-h6" style="margin-bottom: 5px">其他信息</div>
            <q-separator />
            <div class="row q-col-gutter-x-md dialog_form q-pa-md">
              <div class="col-12" style="margin-top: 5px">
                <h5><q-icon name="star" color="red" />排序：</h5>
                <q-input
                  lazy-rules
                  :rules="[(val) => (val && val > 0) || '请输入大于0的排序']"
                  outlined
                  dense
                  v-model.number="isform.goods_sort"
                  type="number"
                  style="max-width: 250px"
                />
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品状态：</h5>
                <q-select
                  outlined
                  dense
                  :rules="[(val) => val !== null || '请选择是否免邮']"
                  v-model="isform.goods_state"
                  option-value="value"
                  option-label="label"
                  :options="[
                    { value: 0, label: '待审核' },
                    { value: 1, label: '上架' },
                    { value: 2, label: '审核不通过' },
                    { value: 3, label: '下架' },
                  ]"
                  emit-value
                  map-options
                  style="max-width: 250px"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        No results
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>
            </div>
          </div>
        </q-tab-panel>

        <q-tab-panel name="alarms">
          <div class="tabsContent">
            <div class="text-h6" style="margin-bottom: 5px">商品详情</div>
            <tiny-mce
              v-model:id="isform.tinymceID"
              v-model:value="isform.goods_content"
              :toolbar="[
                'searchreplace bold italic alignleft aligncenter alignright forecolor fontsizeselect',
              ]"
              menubar="file edit"
              :height="450"
              upload
              @input="tinymcechange"
            />
          </div>
        </q-tab-panel>

        <q-tab-panel name="movies">
          <q-card square flat class="q-mt-lg q-pt-md q-pb-lg">
            <div class="q-pt-sm q-px-lg">
              <!-- {{ isform.goods_attr_format }} -->
              <div class="text-h6" style="margin-bottom: 5px">商品属性</div>
              <q-table
                table-style="max-height: 400px;max-width:100%;"
                flat
                class="cross_table"
                separator="cell"
                table-header-class="my-special-class"
                :rows="isform.goods_attr_format"
                :columns="attr_format.columns"
                row-key="index"
                virtual-scroll
                hide-bottom
              >
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td key="attr_name" :props="props">
                      <q-input
                        v-model="props.row.attr_name"
                        dense
                        outlined
                        :input-style="{ textAlign: 'center' }"
                      />
                    </q-td>
                    <q-td key="attr_value" :props="props">
                      <q-input
                        v-model="props.row.attr_value"
                        :input-style="{ textAlign: 'center' }"
                        dense
                        outlined
                      />
                    </q-td>
                    <q-td key="operation" :props="props">
                      <q-btn
                        flat
                        round
                        dense
                        class="q-mx-xs"
                        color="negative"
                        icon="delete"
                      >
                        <q-menu
                          transition-show="jump-up"
                          transition-hide="jump-down"
                          content-class="text-center"
                          self="bottom left"
                          anchor="top left"
                          :offset="[60, 5]"
                        >
                          <div class="q-px-sm q-pt-md">
                            <q-icon
                              name="info"
                              color="warning"
                              class="q-mr-sm"
                            />
                            是否要删除此行?
                          </div>
                          <div class="q-gutter-x-sm q-pt-sm q-pb-md">
                            <q-btn
                              color="grey-6"
                              unelevated
                              class="no-border-radius text-body2"
                              padding="2px sm"
                              dense
                              label="取消"
                              v-close-popup
                            ></q-btn>
                            <q-btn
                              color="primary"
                              unelevated
                              class="no-border-radius text-body2"
                              padding="2px sm"
                              dense
                              label="确认"
                              v-close-popup
                              @click="deleteData(props.rowIndex)"
                            ></q-btn>
                          </div>
                        </q-menu>
                      </q-btn>
                    </q-td>
                  </q-tr>
                </template>
              </q-table>
              <q-btn
                unelevated
                :ripple="{ color: 'info' }"
                class="q-mt-md full-width"
                style="border: 1px dashed lightgrey; max-width: 100%"
                label="新增属性"
                icon="add"
                @click="addData"
              />
            </div>
          </q-card>
        </q-tab-panel>
      </q-tab-panels>
    </q-form>
  </div>
</template>

<script lang="ts" setup>
import emitter from '@/components/eventbus';
import { goodsAdd, goodsEdit } from '@/api/goods';
import { attr_format } from '../mocklist';
import { useQuasar } from 'quasar';
import { cloneDeep } from 'lodash-es';
import { uploadAxios, uploadAxiosVideo } from '@/api/user';
import draggable from 'vuedraggable';

interface Props {
  form: {
    goods_name?: string; //商品名称
    category_id?: any; //分类id
    goods_type?: number; //商品类型id
    goods_image?: string; //商品主图
    goods_content?: string; //商品详情
    is_free_shipping?: number; //是否免邮
    unit?: string; //台
    goods_sort?: number; //排序
    goods_state?: any; //商品状态（0:待审核,1:上架,2:审核不通过,3:下架）
    goods_attr_format?: Array<any>; //商品属性
    goods_spec_format?: Array<any>; //商品规格
    sku?: Array<any>; //商品sku
    images?: Array<any>; //商品图片
  };
  cateoptions?: []; //所有分类
  goodsTypeoptions?: []; //商品分类
}
const props = withDefaults(defineProps<Props>(), {
  form: () => ({}),
  cateoptions: () => [],
  goodsTypeoptions: () => [],
});

const tab = ref('mails');
const editRef = ref();
const $q = useQuasar();
const yqupload = ref();
const eleUpload = ref();

//上传图片跟视频

//接收兄弟组件传递事件
emitter.on('saveData', async () => {
  console.log(
    'saveDatasaveData',
    isform.value.goods_spec_format,
    isform.value.sku
  );
  let data = cloneDeep(isform.value);
  let deepSku = data.sku;
  //分类ID多选框数组转字符串
  data.category_id = data.category_id.join(',');

  //把表格数据中isform.goods_spec_format里spec_name的值跟isform.sku循环遍历对象的属性进行对比：{ "测试1": "11","测试22":"22"}转成sku_spec_format:[{"spec_name":"测试1","spec_value":"11"},{"spec_name":"测试22","spec_value":"22"}]的形式
  deepSku.forEach((item: any, index: any) => {
    item.sku_name = 'sku_name'; //写死
    isform.value.goods_spec_format.forEach((i: any, d: any) => {
      for (let key in item) {
        if (key === i.spec_name) {
          //添加到deepSku的属性中
          (item['sku_spec_format'] || (item['sku_spec_format'] = [])).push({
            spec_name: i.spec_name,
            spec_value: item[key],
          });
          //删掉deepSku的属性中的值
          if (i.spec_name) {
            delete item[key];
          }
        }
      }
    });
  });
  console.log('最终结果', deepSku);
  data.sku = deepSku;

  IsValidate(data);
});

const updateSort = (e: any) => {
  console.log(e, '调整位置', e.oldIndex, e.newIndex);
};
const tinymcechange = (e: any) => {
  isform.value.goods_content = e + '';
  // console.log('8888', isform.value.goods_content);
};

const Updatetable = (data: any) => {
  console.log('data', data);
  isform.value.sku = data;
};

//删除商品属性
const deleteData = (rowIndex: any) => {
  console.log('deleteData', rowIndex);
  isform.value.goods_attr_format.splice(rowIndex, 1);
};
//增加商品属性
const addData = () => {
  console.log('addData');
  isform.value.goods_attr_format.push({
    attr_name: '',
    attr_value: '',
  });
};
// setTimeout(() => {
//   isform.value.goods_content = 'tinymce1111';
// }, 3000);
//表单验证
const IsValidate = (data: any) => {
  if (editRef.value) {
    editRef.value.validate().then(async function (validate: any) {
      if (validate) {
        console.log('验证通过');
        onSubmit(data);
      } else {
        console.log('验证不通过');
      }
    });
  }
};
//提交数据
const onSubmit = async (data: any) => {
  if (isform.value.goods_id) {
    const res: any = await goodsEdit(data);
    info(res);
    console.log('编辑111', res);
  } else {
    const res: any = await goodsAdd(data);
    info(res);
    console.log('新建角色111', res);
  }
};
//信息返回
const info = (res: any) => {
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
    emit('backList');
  }
};

//上传图片
const importAvatar = () => {
  yqupload.value.importAvatar();
  // avatarUploader.value.pickFiles();
};
//上传商品图片
// const handleThumbnailBeforeUpload = (rawFile: any) => {
//   console.log('handleThumbnailBeforeUpload', rawFile);
//   if (rawFile.size / 1024 / 1024 > 10) {
//     $q.notify({
//       color: 'white',
//       textColor: 'negative',
//       icon: 'cancel',
//       position: 'top',
//       message: '图片/视频大小不能超过 10MB',
//     });
//     return false;
//   }
//   return true;
// };
// const handleThumbnailUpload = (option: any) => {
//   console.log('handleThumbnailUpload', option);
//   let { file } = option;
//   let formData = new FormData();
//   formData.append('file', file);
//   uploadAxios({ image: formData })
//     .then((res) => {
//       console.log('handleThumbnailUpload', res);
//     })
//     .catch(() => {
//       console.log('catch');
//     });
// };
const deleteImage = (index: any) => {
  isform.value.images.splice(index, 1);
};
const handleThumbnailChange = (option: any, str: any) => {
  console.log('handleThumbnailChange', option, str);
  let file = option.raw;
  let formData = new FormData();
  formData.append(str == 'video' ? 'video' : 'image', file);
  let urlAxios =
    str == 'video' ? uploadAxiosVideo(formData) : uploadAxios(formData);
  urlAxios
    .then((res: any) => {
      if (res.code == 200) {
        isform.value.images.push({
          type: str == 'video' ? 1 : 0,
          link: `${process.env.VUE_APP_API_URL}` + res.data.path,
        });
        $q.notify({
          color: 'white',
          textColor: 'positive',
          icon: 'check_circle',
          position: 'top',
          message: res.msg,
        });
      } else {
        $q.notify({
          color: 'white',
          textColor: 'negative',
          icon: 'cancel',
          position: 'top',
          message: res.msg,
        });
      }
      console.log('handleThumbnailUpload', res);
    })
    .catch((erro) => {
      $q.notify({
        color: 'white',
        textColor: 'negative',
        icon: 'cancel',
        position: 'top',
        message: erro,
      });
    });
};

const uploadImg = () => {
  console.log('uploadImg', eleUpload.value);
};
const uploadVideo = () => {
  console.log('uploadVideo', eleUpload.value);
};

const imagePath = (src: any) => {
  let path = '';
  if (src) {
    if (src.startsWith('http') || src.startsWith('https')) {
      return src;
    }
    path = `${process.env.VUE_APP_API_URL}/${src}`;
  }
  return path;
};
//上传商品图片回调

//上传图片回调
const uploadedAvatar = (xhr: any) => {
  console.log('图片状态回调', xhr);
  const response = JSON.parse(xhr.xhr.responseText);
  if (response.code == 200) {
    isform.value.goods_image =
      `${process.env.VUE_APP_API_URL}` + response.data.path;
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: response.msg,
    });
    console.log('图片地址:', isform.value.goods_image);
  } else {
    $q.notify({
      color: 'white',
      textColor: 'negative',
      icon: 'cancel',
      position: 'top',
      message: response.msg,
    });
  }
  console.log('上传图片完成', xhr, response);
  //清空
  yqupload.value.removeUpload();
};

const emit = defineEmits(['update:form', 'backList']);

const isform: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    console.log('props.form', props.form);
    return props.form;
  },
});

//所有分类
const optionsCate: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    return props.cateoptions;
  },
});
//商品分类
const optionsGoodsType: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    return props.goodsTypeoptions;
  },
});
onMounted(() => {
  console.log('onMountedListDialog');
});
</script>
<style scoped lang="scss">
.postage {
  padding: 10px 0;
  h5 {
    font-size: 14px;
    font-weight: 400;
    line-height: 2rem;
    letter-spacing: normal;
  }
}
.q-gutter-x-sm,
.q-gutter-sm {
  margin-left: 15px;
}
::v-deep(.my-special-class) {
  height: 48px;
  background: #fafafa;
}
.uploadBox {
  display: flex;
}

.wallBox {
  position: relative;
  width: 100%;
  // height: 100%;
  max-height: 500px;
  height: auto;
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
  min-height: 150px;
  background: #fff;
  border: 1px solid #e6e6e6;
  padding: 10px;
  box-shadow: 0 1px 5px rgb(0 0 0 / 20%), 0 2px 2px rgb(0 0 0 / 14%),
    0 3px 1px -2px rgb(0 0 0 / 12%);
  .wall {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .tpbox {
      position: relative;
      border: 1px solid #dcdfe6;
      width: 180px;
      height: 180px;
      // overflow: hidden;
      margin-right: 20px;
      margin-bottom: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      .deleteBox {
        top: -15px;
        right: -20px;
        position: absolute;
        display: none;
        z-index: 9999;
      }
    }
    .tpbox:hover {
      .deleteBox {
        display: block;
      }
    }
  }
}
::v-deep(.my-special-class th) {
  font-size: 16px;
}
::v-deep(.my-special-class th) {
  font-size: 16px;
}
@media screen and (max-width: 780px) {
  .wallBox {
    width: 280px;
    .wall {
      justify-content: center;
    }
  }
}
</style>
